﻿using FySystem.Data.OrmA.Attributes;
using FySystem.Data.OrmA.Ext;
using FySystem.Data.OrmA.Reflection;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace FySystem.Data.OrmA.Formatter
{
    class MysqlFormatter : ISqlFormatter
    {
        string ISqlFormatter.ParameterMark { get { return "?"; }}

        string[] ISqlFormatter.KeywordsMark { get; } = new string[] { "`", "`" };

        DbTypes ISqlFormatter.DbType { get; } = DbTypes.Mysql;

        string ISqlFormatter.FormatFields(string value)
        {
            return value;
        }

        string ISqlFormatter.GetPrePKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            return null;
        }

        string ISqlFormatter.GetPostPKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            try
            {
                if (fyPrimaryKey.PrimaryKeyType == PrimaryKeyTypes.AutoIncremental)
                    return "SELECT LAST_INSERT_ID()";
                else
                    return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        string ISqlFormatter.GetMidPKSQL(FyPrimaryKeyAttribute fyPrimaryKey)
        {
            return null;
        }

        string ISqlFormatter.ConvertDbJsonValue(object value)
        {
            throw new Exception("该数据库暂不支持Json格式字段~");
        }

        string ISqlFormatter.ToSingleSQL(string sql)
        {
            try
            {
                return $"{sql} LIMIT 1";
            }
            catch (Exception)
            {
                throw;
            }
        }

        string ISqlFormatter.ToPgQuerySQL(string sql, int pageNumber, int perPage, string orderBy)
        {
            try
            {
                //MySQL的分页，通用函数很难做优化，这里直接用最基础的limit XX, XX来实现，为了您的生命安全，请使用免费的Postgresql替代Mysql
                //对于MySQL大佬，请忽略上面的注释
                long startRow = (pageNumber - 1) * perPage;
                return $"{sql} {orderBy} LIMIT {startRow},{perPage}";
            }
            catch (Exception)
            {
                throw;
            }
        }

        string ISqlFormatter.GenNvlSQL(string fieldName, object[] values)
        {
            try
            {
                if (values.IsNullOrEmpty())
                    throw new Exception("传入参数为空NVLSQL");

                var value = values[0];
                if (value.GetType() == typeof(string))
                    return $"IFNULL({fieldName}, '{value}')";
                else
                    return $"IFNULL({fieldName}, {value})";
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
